package eu.whowie.jast.client;

/**
 * Copyright 2010  Pavel Nemec <nemecp4@gmail.com> <br>
 * <br>
 * License - GPLv3<br>
 *<br>
 * This program is free software; you can redistribute it and/or modify<br>
 * it under the terms of the GNU General Public License as published by<br>
 * the Free Software Foundation; either version 3 of the License, or<br>
 * (at your option) any later version.<br>
 *<br>
 * This program is distributed in the hope that it will be useful,<br>
 * but WITHOUT ANY WARRANTY; without even the implied warranty of<br>
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br>
 * GNU General Public License for more details.<br>
 *<br>
 * You should have received a copy of the GNU General Public License<br>
 * along with this program. If not, see <http://www.gnu.org/licenses/>.<br>
 *<br>
 */
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.logging.Level;
import java.util.logging.Logger;

import eu.whowie.jast.remote.UIRemoteInterface;

/**
 * 
 * @author Pavel Nemec
 * 
 */
public class JastRmiClient {

	Logger logger = Logger.getLogger("JAST_RMI_CLIENT");

	int port = 65000;
	private Registry registry;

	public JastRmiClient() throws RemoteException {

		System.setProperty("java.security.policy", "cfg/server.policy");
		if (System.getSecurityManager() == null) {
			System.setSecurityManager(new SecurityManager());
		}
		registry = LocateRegistry.getRegistry(port);

		logger.log(Level.INFO, "registry succesfully obtained");

	}

	public UIRemoteInterface getUi() throws RemoteException, NotBoundException {
		return (UIRemoteInterface) registry.lookup("JYUI");

	}

	@SuppressWarnings("unchecked")
	public <T extends Remote> void export(T object, String name) {
		if (registry == null) {
			throw new RuntimeException("server  not yet started!");
		}

		T stub;
		try {
			stub = (T) UnicastRemoteObject.exportObject(object, 0);
			logger.log(Level.INFO, name + " bound succesfully");
			registry.rebind(name, stub);
		} catch (RemoteException e) {
			logger.log(Level.SEVERE, name + " not bound");
			e.printStackTrace();
		}
	}
}
